<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/11/28 0028
 * Time: 上午 10:37
 */
namespace app\admin\controller;

use think\Db;
use app\lib\Qiniu;
use think\Controller;
use \think\Request;
use app\common\BaseHelper;

class Files extends Controller{
    /**
     * 获取七牛token
     * @Author   jiating
     * @DateTime 2018-04-20
     * @return   json
     */
    public function token() {
        $Qiniu = new Qiniu();
        return json(['uptoken'=>$Qiniu->getToken()]);
    }

    /**
     * 将上传的每一张图片记录到数据表中
     * @Author   jiating
     * @DateTime 2018-04-27
     * imgUrl  图片地址
     */
    public function record(Request $request) {
        $param = $request->param();
        $id = BaseHelper::getUUID();
        $data = [
            'id' => $id,
            'file_link' => $param['file_link'],
            'created' => time()
        ];

        $add = Db::table('files')->insert($data);
        $code = $add ? '1' : '2';
        return json(['file_id'=>$id,'code'=>$code]);
    }

    /**
     * 图片删除-删除记录及七牛空间中的图片
     * @Author   jiating
     * @DateTime 2018-05-05
     * id  图片记录id
     * imgUrl  图片地址
     * @return   json
     */
    public function delete(Request $request) {
        $url = $this->request->param('file_link');
        $id = $this->request->param('id');
        $key =  substr(strrchr($url, '/'), 1);
        // return $key;
        $Qiniu = new Qiniu();
        $res = $Qiniu->delImg($key);  //删除图片
        if($res == NULL){
            Db::table('files')->where('id',$id)->delete();  //删除总表记录
            //Db::table('image')->where('imgUrl', $url)->delete();  //删除总表记录
            return json(['message'=>'success','code'=>'1']);
        }else{
            return json(['message'=>'删除失败','code'=>'2']);
        }
    }
}